<!--  -->
<template>
  <el-container style="margin:0px auto;width:80%">
    <el-header style="text-align:left;padding:10px;border-bottom:2px solid #787878">
      <strong>
        <font color="red">全部商品</font>
      </strong>
    </el-header>
    <el-main>
      <el-table
        ref="cartTable"
        :data="tableData"
        align="center"
        @selection-change="selectionChange"
        :header-cell-style="{background:'#eef1f6',color:'#606266'}"
      >
        <el-table-column type="selection"></el-table-column>
        <el-table-column label="商品图标">
          <template slot-scope="scope">
            <el-image style="width: 100px; height: 100px" :src="scope.row.produce_icon"></el-image>
          </template>
        </el-table-column>
        <el-table-column fixed prop="produce_name" label="商品名称"></el-table-column>
        <el-table-column prop="produce_price" label="单价"></el-table-column>
        <el-table-column width="180" label="数量">
          <template slot-scope="scope">
            <el-input-number
              :min="1"
              :max="scope.row.produce_max"
              v-model="scope.row.produce_quantity"
              @change="(value)=>{quantityChange(value,scope.$index)}"
              size="small"
              label="描述文字"
            ></el-input-number>
          </template>
        </el-table-column>
        <el-table-column prop="money" label="金额"></el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button type="danger" size="mini" @click="deleteProduce(scope.$index)">移除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <br />
      <br />
      <div style="margin:0px auto;padding:10px;border:0.5px solid #E0E0E0">
        <el-row :gutter="20" style="margin: 10px auto;">
          <el-col :span="6">
            <div class="grid-content bg-purple" style="padding: 5px;float:left">
              <el-button type="danger" size="small" @click="deleteSelect">删除所选商品</el-button>
            </div>
          </el-col>
          <el-col :span="6">
            <!-- <div class="grid-content bg-purple" style="padding: 5px"></div> -->
          </el-col>

          <el-col :span="6" style="float:right;text-align:right"></el-col>
          <el-col :span="6" style="float:right;text-align:right">
            <div class="grid-content bg-purple" style="padding: 5px">
              <!-- <el-tag type="danger" effect="plain" :hit="false">{{total}}元</el-tag> -->
              总价:
              <strong>
                <font color="red">￥{{total}}</font>
              </strong>
              <el-button size="small" type="danger" style="width:100px" @click="payFor">支付</el-button>
            </div>
          </el-col>
        </el-row>
      </div>
    </el-main>
    <el-footer></el-footer>
  </el-container>
</template>

<script>
//这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
//例如：import 《组件名称》 from '《组件路径》';

export default {
  name: "App",
  //import引入的组件需要注入到对象中才能使用
  components: {},
  data() {
    //这里存放数据
    return {
      total: 0.0,
      checked: false,
      tableData: [],
      select: [],
    };
  },
  //监听属性 类似于data概念
  computed: {},
  //监控data中的数据变化
  watch: {},
  //方法集合
  methods: {
    payFor() {
      // let url = process.env.URL_HEAD+"/payment/payment/confirm/select";
      // this.$http
      //   .post(url, this.select, {
      //     withCredentials: true,
      //   })
      //   .then((data) => {});
      if (this.select.length <= 0) {
        const h = this.$createElement;
        this.$notify({
          title: "提示",
          message: h("i", { style: "color: teal" }, "请至少选择一件商品"),
          type: "warning",
        });
      } else {
        this.$router.push({ name: "Payment", params: { select: this.select } });
      }
    },
    selectionChange(selection) {
      this.select = [];
      this.total = 0;
      for (let i = 0; i < selection.length; i++) {
        this.select.push(selection[i].produce_id);
        this.total = this.total + selection[i].money;
      }
    },
    deleteSelect() {
      //console.log(this.$refs.cartTable.store.states.selection);
      this.$confirm("确认要删除所选商品吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          let array = [];
          let temp = this.$refs.cartTable.store.states.selection;
          for (let i = 0; i < temp.length; i++) {
            array.push(temp[i].produce_id);
          }
          let url =
            process.env.URL_HEAD + "/sc/shoppingcart/shoppingcart/delete";
          this.$http
            .post(url, array, {
              headers: {},
              withCredentials: true,
            })
            .then((data) => {
              this.$message({
                type: "success",
                message: "删除成功!",
              });
              this.tableData = [];
              this.getShoppingCartInfo();
            });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    deleteProduce(index) {
      this.$confirm("确认要删除该商品吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          let id = this.tableData[index].produce_id;
          let array = [id];
          let url =
            process.env.URL_HEAD + "/sc/shoppingcart/shoppingcart/delete";
          this.$http
            .post(url, array, {
              withCredentials: true,
            })
            .then((data) => {
              this.$message({
                type: "success",
                message: "删除成功!",
              });
              this.tableData = [];
              this.getShoppingCartInfo();
            });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    getShoppingCartInfo() {
      let url = process.env.URL_HEAD + "/sc/shoppingcart/shoppingcart/cart";
      let str = this.randomString(20);
      let random = Math.random();
      this.$http
        .get(url, {
          headers: {
            test: str,
          },
          params: {},
          withCredentials: true,
        })
        .then((data) => {
          for (let i = 0; i < data.body.cart.length; i++) {
            let count =
              data.body.cart[i].producePrice *
              data.body.cart[i].produceQuantity;
            //this.total = this.total + count;
            this.tableData.push({
              produce_id: data.body.cart[i].produceId,
              produce_name: data.body.cart[i].produceName,
              produce_price: data.body.cart[i].producePrice,
              produce_quantity: data.body.cart[i].produceQuantity,
              produce_icon: data.body.cart[i].produceIcon,
              produce_max: data.body.cart[i].produceStock,
              money: count,
            });
          }
          //console.log("tableDatat", this.tableData);
        });
    },
    quantityChange(value, index) {
      let id = this.tableData[index].produce_id;
      let url = process.env.URL_HEAD + "/sc/shoppingcart/shoppingcart/update";
      this.$http
        .post(
          url,
          {
            produceId: id,
            produceQuantity: this.tableData[index].produce_quantity,
          },
          {
            withCredentials: true,
          }
        )
        .then((data) => {});
      // this.tableData = [];
      // this.getShoppingCartInfo();
      this.tableData[index].money =
        this.tableData[index].produce_quantity *
        this.tableData[index].produce_price;
      this.total = 0;
      let temp = this.$refs.cartTable.store.states.selection;
      for (let i = 0; i < temp.length; i++) {
        this.total += temp[i].money;
      }
    },

    randomString(len) {
      len = len || 32;
      /****默认去掉了容易混淆的字符oOLl,9gq,Vv,Uu,I1****/
      var $chars = "ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678";
      var maxLen = $chars.length;
      var str = "";
      for (let i = 0; i < len; i++) {
        str += $chars.charAt(Math.floor(Math.random() * maxLen));
      }
      return str;
    },
  },
  //生命周期 - 创建完成（可以访问当前this实例）
  created() {
    this.getShoppingCartInfo();
  },
  //生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {},
  beforeCreate() {}, //生命周期 - 创建之前
  beforeMount() {}, //生命周期 - 挂载之前
  beforeUpdate() {}, //生命周期 - 更新之前
  updated() {}, //生命周期 - 更新之后
  beforeDestroy() {}, //生命周期 - 销毁之前
  destroyed() {}, //生命周期 - 销毁完成
  activated() {}, //如果页面有keep-alive缓存功能，这个函数会触发
};
</script>
<style>
.el-header,
.el-footer {
  /* background-color: #b3c0d1;
  color: #333; */
  text-align: center;
  line-height: 60px;
}

.el-aside {
  background-color: #d3dce6;
  color: #333;
  text-align: center;
  line-height: 200px;
}

.el-main {
  /* background-color: #e9eef3;
  color: #333; */
  text-align: center;
}

body > .el-container {
  margin-bottom: 40px;
}

.el-container:nth-child(5) .el-aside,
.el-container:nth-child(6) .el-aside {
  line-height: 260px;
}

.el-container:nth-child(7) .el-aside {
  line-height: 320px;
}
.el-col {
  border-radius: 4px;
}
/* .bg-purple-dark {
  background: #99a9bf;
}
.bg-purple {
  background: #d3dce6;
}
.bg-purple-light {
  background: #e5e9f2;
} */
.grid-content {
  border-radius: 4px;
  min-height: 36px;
}
.row-bg {
  padding: 10px 0;
  background-color: #f9fafc;
}
</style>